import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../model/chat_message.dart';
import '../model/message_entity.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({super.key});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final TextEditingController _textController = TextEditingController();
  final List<ChatMessage> _messages = [];
  // 定义 WebSocketChannel 对象
  IOWebSocketChannel? channel;
  // 定义定时器
  Timer? heartbeatTimer;
  // 定义心跳间隔时间（这里设置为 5 秒）
  final Duration heartbeatInterval = Duration(seconds: 5);

  Uri wsUrl = Uri.parse('ws://119.3.198.149:8082/chat');
  @override
  void initState() {
    super.initState();
    connect();
  }

  @override
  void dispose() {
    stopHeartbeat();
    channel?.sink.close();
    super.dispose();
  }

  void connect() async {
    try {
      channel = IOWebSocketChannel.connect(wsUrl);
      await channel?.ready;
      sentConnectMsg();
      // 监听服务器发送的消息
      channel?.stream.listen(
            (message) {
          print("接收到消息" + message);
          Map<String, dynamic> jsonMap = json.decode(message);
          // 将 Map 转换为 MessageEntity 对象
          MessageEntity messageEntity = MessageEntity.fromJson(jsonMap);
          setState(() {
            // 将接收到的消息添加到消息列表中
            _messages.add(ChatMessage(text: messageEntity.content!, isMe: false));
          });
        },
        onError: (error) {
          print('WebSocket 连接出错: $error');
          // 出错时停止心跳定时器
          stopHeartbeat();
        },
        onDone: () {
          print('WebSocket 连接已关闭');
          // 连接关闭时停止心跳定时器
          stopHeartbeat();
        },
      );
      // 启动心跳定时器
      startHeartbeat();
    } on SocketException catch (e) {
      print(e);
    } on WebSocketChannelException catch (e) {
      print(e);
    }
  }
  // 启动心跳定时器
  void startHeartbeat() {
    heartbeatTimer = Timer.periodic(heartbeatInterval, (timer) {
      if (channel?.sink != null) {
        sendHeartMessage();
      }
    });
  }

  // 停止心跳定时器
  void stopHeartbeat() {
    heartbeatTimer?.cancel();
    heartbeatTimer = null;
  }
  // 发送消息
  void _sendMessage() {
    if (_textController.text.isNotEmpty) {
      MessageEntity messageEntity = MessageEntity();
      messageEntity.type = "message";
      messageEntity.content = _textController.text;
      channel?.sink.add(messageEntity.toString());
      setState(() {
        _messages.add(ChatMessage(text: messageEntity.content!, isMe: true));
      });
      _textController.clear();
    }
  }
  void sendHeartMessage() {
    MessageEntity messageEntity = MessageEntity();
    messageEntity.type = "heartbeat";
    messageEntity.content = "ping";
    channel?.sink.add(messageEntity.toString());
  }
  void sentConnectMsg() {
    MessageEntity messageEntity = MessageEntity();
    messageEntity.type = "bind";
    messageEntity.content = "100001";
    channel?.sink.add(messageEntity.toString());
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('聊天窗口'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                return _buildMessage(_messages[index]);
              },
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _textController,
                    decoration: const InputDecoration(
                      hintText: '输入消息',
                    ),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.send),
                  onPressed: _sendMessage,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMessage(ChatMessage message) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 10.0),
      child: Row(
        mainAxisAlignment:
            message.isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: [
          if (!message.isMe) const CircleAvatar(child: Text('他')),
          Container(
            padding: const EdgeInsets.all(12.0),
            margin: const EdgeInsets.symmetric(horizontal: 8.0),
            decoration: BoxDecoration(
              color: message.isMe ? Colors.blue : Colors.grey[300],
              borderRadius: BorderRadius.circular(8.0),
            ),
            child: Text(
              message.text,
              style: TextStyle(
                color: message.isMe ? Colors.white : Colors.black,
              ),
            ),
          ),
          if (message.isMe) const CircleAvatar(child: Text('我')),
        ],
      ),
    );
  }
}
